package cluster

import (
	raftboltdb "github.com/hashicorp/raft-boltdb/v2"
	"strconv"
	"strings"
)

// Config save cluster ips
type Config struct {
	store *raftboltdb.BoltStore
}

var clusterIp = []byte("cluster.ip")
var clusterId = []byte("cluster.id")

func NewConfig(path string) *Config {
	store, err := raftboltdb.NewBoltStore(path)
	if err != nil {
		panic(err)
	}
	return &Config{store: store}
}

func (c *Config) NeedInit() bool {
	if v, err := c.store.Get(clusterIp); err == nil {
		return v == nil && len(v) == 0
	} else {
		return true
	}
}

func (c *Config) GetCluster() ([]string, int) {
	hosts, err := c.store.Get(clusterIp)
	if err != nil {
		panic(err)
	}
	idBytes, err := c.store.Get(clusterId)
	if err != nil {
		panic(err)
	}
	id, err := strconv.Atoi(string(idBytes))
	if err != nil {
		panic(err)
	}
	return strings.Split(string(hosts), ","), id
}

func (c *Config) SaveCluster(ips []string, id int) error {
	value := strings.Join(ips, ",")
	err := c.store.Set(clusterIp, []byte(value))
	if err != nil {
		return err
	}
	err = c.store.Set(clusterId, []byte(strconv.Itoa(id)))
	if err != nil {
		return err
	}
	return nil
}
